from django.shortcuts import render,redirect

from sm_system.views import COOKIE_NAME
from sm_system.models import *
from django.http import HttpResponse
# Create your views here.

#总部功能
def hq_index(request):
    supplier = SupplierInfo.objects.all()
    context = {"suppliers": supplier}
    return render(request, 'supplier/hq-supplier.html', context)

#分部功能
def index(request):
    supermarket_id = str(request.COOKIES.get(COOKIE_NAME))[0:4]
    suppliers = SupplierInfo.objects.filter(supermarket_id=supermarket_id)
    context={"suppliers":suppliers}
    return render(request,'supplier/supplier.html',context)


def update(request, id):

    supplier = SupplierInfo.objects.get(id=id)
    context = {"supplier": supplier}
    return render(request, 'supplier/supplierUpdate.html', context)


def update_form(request):
    if request.POST:
        id = request.POST['id']
        supplier = SupplierInfo.objects.get(id=id)
        supplier.name = request.POST['name']
        supplier.contact = request.POST['contact']
        supplier.save()

    return redirect('/juniorAdmin/supplier_info/')


def add(request):

    return render(request, 'supplier/supplierAdd.html')


def add_form(request):
    if request.POST:
        supermarket_id =str(request.COOKIES.get(COOKIE_NAME))[0:4]
        supplier=SupplierInfo()
        supplier.id = request.POST['id']
        supplier.name = request.POST['name']
        supplier.contact = request.POST['contact']
        supplier.supermarket_id=supermarket_id
        supplier.save()

    return redirect('/juniorAdmin/supplier_info/')


def delete(request,id):
    supplier = SupplierInfo.objects.get(id=id)
    supplier.delete()
    return redirect('/juniorAdmin/supplier_info/')


